<?php
ob_start();

require_once('connect.php');
require_once('includes/user.class.php');

$database = Database::getInstance();
session_start();
$user = new User();
$alert = null;

require_once('partials/header.php'); //wczytaj header i menu

if (isset($_POST['login']) && isset($_POST['password'])) {
    $login = htmlentities(trim($_POST['login']));
    $password = hash('sha256', htmlentities(trim($_POST['password'])));

    $user_query = $database->dbh->prepare("
        SELECT COUNT(id) as counted, id
        FROM student
        WHERE login='$login' and password='$password'
        LIMIT 1
        ");
    if ($user_query->execute()) {
        $selected_user = $user_query->fetch(PDO::FETCH_ASSOC);
        if ($selected_user['counted'] == '1') {
            $_SESSION['login'] = $login;
            $_SESSION['uid'] = $selected_user['id'];
            $_SESSION['alert'] = array('Witaj <strong>' . $login . '</strong>! Udało Ci się pomyślnie zalogować do systemu!', 'success');
            header('Location: main.php');
        } else {
            $alert = array('Podano złe dane, spróbuj ponownie.', 'danger');
        }
    } else {
        $alert = array('Wystąpił błąd przy próbie logowania, spróbuj ponownie.', 'danger');
    }
}?>


<?php
    if ($user -> is_logged()) header('Location: main.php');
?>
    <div class="container">

    <?php
    //wyświetl informację o logowaniu jeśli występuje
        $user->show_alert($alert);
        empty($alert);
    ?>

        <div class="text-center">
            <img class="logo-image" src="img/aghlogo.png"/>
            <h1><span style="color: #82B900;">Wirtualny</span> Starosta</h1>
        </div>

        <section class="window text-center">

            <form action="index.php" method="POST">

                <p class="login-line-register"><input type="text" name="login" id="login" class="login-input-register" placeholder="LOGIN"></p>
                <p class="login-line-register"><input type="password" name="password" id="password" class="login-input-register" placeholder="HASŁO"></p>

                <input type="submit" name="submit" value="Zaloguj" class="login-button"/>
                <span class="login-options-text"> Nie masz konta? <a href='register.php'>Zarejestruj się</a></span>
                <span class="login-options-text"> Nie pamiętasz hasła? <a href='recoverpass.html'>Przypomnij</a></span>

            </form>
        </section>

    </div>



<?php
require_once('partials/footer.php'); //wczytaj stopkę
ob_end_flush();